import Message from 'tdesign-miniprogram/message/index';
import { postAPI } from '~/api/post';
import { bookAPI } from '~/api/book';
const config = require('~/config/index.js').default;
const authUtils = require('~/utils/auth.js');
const uiHelper = require('~/utils/ui-helper.js');

// 获取应用实例
const app = getApp();

Page({
  data: {
    // 欢迎卡片状态
    showWelcomeCard: false,
    userInfo: {},
    userTitle: '流萤',
    userId: '',
    // 每日一句猜书名游戏
    dailyQuote: {},
    // 弹窗状态
    showFullPopup: false,
    // 用户输入的答案
    userAnswer: '',
    // 我的书摘列表
    myPosts: [],
    // 加载状态
    loading: false,
    // 首次加载状态（用于显示骨架屏）
    firstLoading: true,
    // 每日一句加载状态
    dailyQuoteLoading: true,
    // 下拉刷新状态
    refreshing: false,
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      hasMore: true
    },
    // 页面滚动位置
    scrollTop: 0,
    // 协议检查标志（防止重复检查）
    privacyChecked: false,
    // 错误状态
    hasError: false,
    errorMessage: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 确保用户已登录后再加载数据
    this.ensureUserLogin();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData();
    
    // 检查隐私协议（仅在用户已登录时）
    this.checkPrivacyAgreementOnShow();
    
    // 检查是否需要显示欢迎卡片
    this.checkWelcomeCard();
  },

  /**
   * 确保用户已登录
   */
  ensureUserLogin() {
    const userInfo = wx.getStorageSync('userInfo');
    const userId = wx.getStorageSync('userId');
    
    if (userInfo && userId) {
      console.log('用户已登录，用户ID:', userId);
      // 更新全局数据
      app.globalData.userInfo = userInfo;
      app.globalData.userId = userId;
      
      // 获取用户称号
      const userTitle = wx.getStorageSync('userTitle') || 
                       app.globalData.userProfile?.title || 
                       '流萤';
      
      // 设置欢迎卡片数据
      this.setData({
        userInfo: userInfo,
        userId: userId.toString(),
        userTitle: userTitle
      });
      
      // 检查是否需要显示欢迎卡片
      this.checkWelcomeCard();
      
      // 加载数据
      this.loadDailyQuote();
      this.loadMyPosts();
    } else {
      console.log('用户未登录，跳转到登录页面');
      wx.navigateTo({
        url: '/pages/login/login'
      });
    }
  },



  /**
   * 页面滚动事件
   */
  onPageScroll(e) {
    const { scrollTop } = e;
    this.setData({ scrollTop });
  },

  /**
   * 加载每日一句
   */
  async loadDailyQuote() {
    this.setData({ dailyQuoteLoading: true });
    
    try {
      // 检查本地是否已有已答对的数据
      const { dailyQuote } = this.data;
      if (dailyQuote && dailyQuote.correct === true && dailyQuote.content) {
        this.setData({ dailyQuoteLoading: false });
        return; // 如果已答对，直接返回，不再调用接口
      }

      // 检查本地是否有未答对的数据，如果有且内容完整，也使用本地数据
      if (dailyQuote && dailyQuote.content && dailyQuote.id) {
        this.setData({ dailyQuoteLoading: false });
        return;
      }

      // 使用统一的 API 调用获取每日一句
      const response = await bookAPI.getDailyQuote(app.globalData.userId || 1);

      if (response && response.code === 200) {
        const quoteData = response.data;
        
        
        
        // 确保 quoteData 和 content 存在
        if (!quoteData || !quoteData.content) {
          console.warn('每日一句数据不完整，使用默认数据');
          this.setDefaultQuote();
          return;
        }
        
        // 处理数据，适配后端格式并添加前端需要的字段
        const processedQuote = {
          // 后端字段映射
          id: parseInt(quoteData.id) || 1, // 确保id是数字类型
          content: quoteData.content,
          bookTitle: quoteData.bookTitle,
          author: quoteData.author,
          submittedBy: quoteData.submittedBy,
          submittedAt: quoteData.submittedAt,
          maxLength: quoteData.maxLength,
          correct: quoteData.correct,
          // 前端额外字段
          shortContent: quoteData.content && quoteData.content.length > 80 ? 
            quoteData.content.substring(0, 80) + '...' : 
            quoteData.content,
          // 根据后端 correct 字段决定展示状态
          isExpanded: false, // 默认不展开
          isAnswered: quoteData.correct === true, // 如果已答对，标记为已回答
          isCorrect: quoteData.correct === true, // 如果已答对，标记为答对
          // 已答对时不显示答题结果信息，只显示简洁的书本信息
          resultMessage: '' // 已答对时不显示"答对啦！"
        };

        this.setData({ 
          dailyQuote: processedQuote,
          dailyQuoteLoading: false
        });
      } else {
        // 如果接口返回失败，显示错误信息
        this.setData({ dailyQuoteLoading: false });
        Message.error({
          context: this,
          content: '获取每日一句失败，请重试',
          duration: 2000
        });
      }
    } catch (error) {
      this.setData({ dailyQuoteLoading: false });
      
      // 任何错误都显示错误信息
      Message.error({
        context: this,
        content: '获取每日一句失败，请重试',
        duration: 2000
      });
    }
  },



  /**
   * 设置默认每日一句（接口失败时的备用方案）
   */
  setDefaultQuote() {
    const defaultQuote = {
      // 后端格式字段
      id: 1,
      content: '人生若只如初见，何事秋风悲画扇。等闲变却故人心，却道故人心易变。',
      bookTitle: '纳兰词',
      author: '纳兰性德',
      submittedBy: '简语',
      submittedAt: '2025-01-27',
      maxLength: 180,
      correct: null, // 未答题状态，显示猜书名界面
      // 前端额外字段
      shortContent: '人生若只如初见，何事秋风悲画扇。等闲变却故人心，却道故人心易变。',
      // 根据后端 correct 字段决定展示状态
      isExpanded: false, // 默认不展开
      isAnswered: false, // null 表示未答题
      isCorrect: false, // null 表示未答题
      resultMessage: ''
    };
    
    this.setData({ 
      dailyQuote: defaultQuote
    });
  },

  /**
   * 加载我的书摘列表
   */
  async loadMyPosts(refresh = false) {
    // 检查登录状态
    if (!authUtils.isLoggedIn()) {
      return;
    }
    
    if (this.data.loading) return;

    const { pagination } = this.data;
    
    if (refresh) {
      pagination.page = 1;
      pagination.hasMore = true;
      this.setData({ 
        hasError: false,
        errorMessage: ''
      });
    }

    if (!pagination.hasMore) return;

    // 首次加载显示骨架屏，其他时候显示普通loading
    this.setData({ 
      loading: true,
      firstLoading: refresh ? false : (this.data.myPosts.length === 0)
    });

    try {
      const userId = wx.getStorageSync('userId');
      
      // 检查 userId 是否存在
      if (!userId) {
        console.warn('用户ID不存在，无法加载书摘');
        this.setData({
          myPosts: [],
          loading: false,
          pagination: {
            ...pagination,
            hasMore: false
          }
        });
        
        // 提示用户重新登录
        wx.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 2000
        });
        
        // 跳转到登录页面
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }, 2000);
        return;
      }

      const params = {
        page: pagination.page,
        pageSize: pagination.pageSize,
        userId: userId
      };

      const response = await postAPI.getMyQuotes(params);
      const { data, total } = response;

      // 确保 data 是数组
      if (!Array.isArray(data)) {
        console.warn('书摘数据格式错误，使用空数组');
        this.setData({
          myPosts: refresh ? [] : this.data.myPosts,
          pagination: {
            ...pagination,
            page: pagination.page + 1,
            hasMore: false
          },
          loading: false
        });
        return;
      }

      // 格式化数据并获取书籍信息
      const formattedPosts = await Promise.all(data.filter(quote => quote && quote.quoteId).map(async (quote) => {
        let bookInfo = {
          bookId: quote.bookId,
          title: quote.bookTitle || '未知书籍',
          author: quote.author || '未知作者',
          coverUrl: quote.coverUrl || '/static/home/card0.png'
        };

        // 根据 bookId 获取真实的书籍信息
        if (quote.bookId) {
          try {
            const bookResponse = await bookAPI.getBookById(quote.bookId);
            if (bookResponse && bookResponse.code === 200 && bookResponse.data) {
              const bookData = bookResponse.data;
              let coverUrl = bookData.coverUrl || '/static/home/card0.png';
              
              // 处理封面URL拼接
              if (coverUrl && !coverUrl.startsWith('http') && !coverUrl.startsWith('/static/')) {
                coverUrl = `${config.baseUrl}${coverUrl}`;
              }
              
              bookInfo = {
                bookId: bookData.bookId,
                title: bookData.title || '未知书籍',
                author: bookData.author || '未知作者',
                coverUrl: coverUrl,
                // 添加书籍统计信息
                totalLikeCount: bookData.totalLikeCount || 0,
                totalCommentCount: bookData.totalCommentCount || 0,
                totalFavoriteCount: bookData.totalFavoriteCount || 0,
                totalQuoteCount: bookData.totalQuoteCount || 0,
                isLikedByCurrentUser: bookData.isLikedByCurrentUser || false,
                isFavoritedByCurrentUser: bookData.isFavoritedByCurrentUser || false
              };
            }
          } catch (error) {
            console.warn(`获取书籍信息失败，bookId: ${quote.bookId}`, error);
            // 使用默认信息，不抛出错误
          }
        } else {
          // 如果没有 bookId，也要处理 coverUrl 拼接
          let coverUrl = bookInfo.coverUrl;
          if (coverUrl && !coverUrl.startsWith('http') && !coverUrl.startsWith('/static/')) {
            coverUrl = `${config.baseUrl}${coverUrl}`;
            bookInfo.coverUrl = coverUrl;
          }
        }

        const formattedQuote = {
          ...quote,
          // 确保 ID 字段正确映射
          id: quote.id || quote.quoteId,
          quoteId: quote.quoteId || quote.id,
          createdAt: this.formatTime(quote.createdAt),
          isExpanded: false, // 默认不展开
          isThoughtsExpanded: false, // 默认不展开感想
          // 确保感想字段正确映射
          userFeel: quote.userFeel || quote.reflection_text || '',
          book: bookInfo,
          user: {
            nickname: app.globalData.userProfile?.nickname || '书虫小明',
            avatar: app.globalData.userProfile?.avatar || '/static/avatar1.png',
            title: app.globalData.userProfile?.title || '初级书虫'
          }
        };
        

        
        return formattedQuote;
      }));
      
      // 过滤掉空值
      const validPosts = formattedPosts.filter(post => post !== null);

      const newPosts = refresh ? validPosts : [...this.data.myPosts, ...validPosts];
      const newHasMore = (refresh ? validPosts.length : this.data.myPosts.length + validPosts.length) < total;
      

      
      this.setData({
        myPosts: newPosts,
        pagination: {
          ...pagination,
          page: pagination.page + 1,
          hasMore: newHasMore
        },
        loading: false
      });
    } catch (error) {
      console.error('加载我的书摘失败:', error);
      this.setData({ 
        loading: false,
        firstLoading: false,
        hasError: true,
        errorMessage: '加载失败，请检查网络后重试'
      });
      
      // 只有在非首次加载时才显示toast提示
      if (this.data.myPosts.length > 0) {
        Message.error({
          context: this,
          content: '加载失败，请重试',
          duration: 2000
        });
      }
    }
  },

  /**
   * 下拉刷新（scroll-view）
   */
  async onRefresh() {
    this.setData({ refreshing: true });
    await this.loadMyPosts(true);
    await this.loadDailyQuote();
    this.setData({ refreshing: false });
  },

  /**
   * 重试加载数据
   */
  async retryLoadData() {
    this.setData({
      hasError: false,
      errorMessage: ''
    });
    await this.loadMyPosts(true);
  },

  /**
   * 下拉刷新（页面级，保持兼容）
   */
  async onPullDownRefresh() {
    await this.onRefresh();
    wx.stopPullDownRefresh();
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    this.loadMyPosts();
  },

  /**
   * 刷新数据
   */
  async refreshData() {
    // 检查是否已答对，如果已答对则跳过每日一句刷新
    const { dailyQuote } = this.data;
    if (!dailyQuote || dailyQuote.correct !== true) {
      await this.loadDailyQuote();
    } 
    await this.loadMyPosts(true);
  },

  /**
   * 发布书摘
   */
  goPublish() {

    
    // 检查用户登录状态
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    wx.navigateTo({
      url: '/pages/release/index',
      success: () => {

      },
      fail: (error) => {

        wx.showToast({
          title: '页面跳转失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },





  /**
   * 点击书摘卡片
   */
  onQuoteTap(e) {
    const { quote } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/quote-detail/index?id=${quote.id}`
    });
  },

  /**
   * 展开/收起书摘内容
   */
  onExpandContent(e) {
    const { quoteId } = e.currentTarget.dataset;
    const { myPosts } = this.data;
    const postIndex = myPosts.findIndex(post => post.id === quoteId);
    
    if (postIndex !== -1) {
      myPosts[postIndex].isExpanded = !myPosts[postIndex].isExpanded;
      this.setData({ myPosts: [...myPosts] });
    }
  },

  /**
   * 展开/收起感想内容
   */
  onExpandThoughts(e) {
    const { quoteId } = e.currentTarget.dataset;
    const { myPosts } = this.data;
    const postIndex = myPosts.findIndex(post => post.id === quoteId);
    
    if (postIndex !== -1) {
      myPosts[postIndex].isThoughtsExpanded = !myPosts[postIndex].isThoughtsExpanded;
      this.setData({ myPosts: [...myPosts] });
    }
  },

  /**
   * 点赞 - 添加防抖和乐观更新
   */
  onLike: uiHelper.debounce(async function(e) {
    const { quoteId, isLiked } = e.currentTarget.dataset;
    
    // 先更新UI，提升用户体验
    this.updateQuoteLikeStatus(quoteId, isLiked);
    
    try {
      if (isLiked) {
        await postAPI.likeQuote(quoteId);
      } else {
        await postAPI.unlikeQuote(quoteId);
      }
    } catch (error) {
      // 操作失败，回滚UI状态
      this.updateQuoteLikeStatus(quoteId, !isLiked);
      Message.error({
        context: this,
        content: '操作失败，请重试',
        duration: 2000
      });
    }
  }, 500),

  /**
   * 收藏 - 添加防抖和乐观更新
   */
  onCollect: uiHelper.debounce(async function(e) {
    const { quoteId, isCollected } = e.currentTarget.dataset;
    
    // 先更新UI，提升用户体验
    this.updateQuoteCollectStatus(quoteId, isCollected);
    
    try {
      if (isCollected) {
        await postAPI.collectQuote(quoteId);
      } else {
        await postAPI.uncollectQuote(quoteId);
      }
    } catch (error) {
      // 操作失败，回滚UI状态
      this.updateQuoteCollectStatus(quoteId, !isCollected);
      Message.error({
        context: this,
        content: '操作失败，请重试',
        duration: 2000
      });
    }
  }, 500),

  /**
   * 评论
   */
  onComment(e) {
    const { postId } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/post-detail/index?id=${postId}&tab=comments`
    });
  },

  /**
   * 分享
   */
  onShare(e) {
    const { post } = e.detail;
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },

  /**
   * 更新书摘点赞状态
   */
  updatePostLikeStatus(postId, isLiked) {
    const { myPosts } = this.data;
    const postIndex = myPosts.findIndex(post => post.id === postId);
    
    if (postIndex !== -1) {
      const post = myPosts[postIndex];
      post.isLiked = isLiked;
      post.likeCount = isLiked ? (post.likeCount || 0) + 1 : Math.max(0, (post.likeCount || 0) - 1);
      
      this.setData({
        myPosts: [...myPosts]
      });
    }
  },

  /**
   * 更新书摘收藏状态
   */
  updatePostCollectStatus(postId, isCollected) {
    const { myPosts } = this.data;
    const postIndex = myPosts.findIndex(post => post.id === postId);
    
    if (postIndex !== -1) {
      const post = myPosts[postIndex];
      post.isCollected = isCollected;
      post.collectCount = isCollected ? (post.collectCount || 0) + 1 : Math.max(0, (post.collectCount || 0) - 1);
      
      this.setData({
        myPosts: [...myPosts]
      });
    }
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;
    
    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return Math.floor(diff / minute) + '分钟前';
    } else if (diff < day) {
      return Math.floor(diff / hour) + '小时前';
    } else if (diff < 7 * day) {
      return Math.floor(diff / day) + '天前';
    } else {
      return date.toLocaleDateString();
    }
  },

  // ==================== 猜书名游戏相关方法 ====================

  /**
   * 点击句子处理
   */
  onQuoteClick() {
    const { dailyQuote } = this.data;
    
    // 如果已经答过题，切换展开状态
    if (dailyQuote.isAnswered) {
      this.setData({
        'dailyQuote.isExpanded': !dailyQuote.isExpanded
      });
      return;
    }
    
    // 未答题时显示弹窗
    this.setData({
      showFullPopup: true,
      userAnswer: '' // 清空之前的答案
    });
  },





  /**
   * 关闭全文弹窗
   */
  closeFullPopup() {
    this.setData({
      showFullPopup: false
    });
  },

  /**
   * 输入框变化处理
   */
  onAnswerInput(e) {
    this.setData({
      userAnswer: e.detail.value
    });
  },

  /**
   * 提交答案
   */
  async submitAnswer() {
    const { userAnswer, dailyQuote } = this.data;
    
    if (!userAnswer.trim()) {
      Message.warning({
        context: this,
        content: '请输入书名',
        duration: 2000
      });
      return;
    }
    
    // 关闭弹窗
    this.setData({
      showFullPopup: false
    });
    
    // 调用检查答案方法
    await this.checkAnswer(userAnswer);
  },

  /**
   * 检查答案（使用统一 API 调用）
   */
  async checkAnswer(userAnswer = '') {
    const { dailyQuote } = this.data;
    
    try {
      // 准备发送的数据
      const requestData = {
        id: parseInt(dailyQuote.id) || 1, // 题目ID，确保是数字类型
        userId: app.globalData.userId || 1, // 用户ID，确保是数字类型
        answer: userAnswer || dailyQuote.bookTitle || '' // 答案，确保是字符串类型
      };
      

      
      // 使用统一的 API 调用检查答案
      const response = await bookAPI.submitDailyQuoteAnswer(requestData);

      if (response && response.code === 200) {
        const result = response.data;
        
        if (result.correct) {
          // 答案正确，显示完整信息（只在第一次答对时显示）
          const updatedQuote = {
            ...dailyQuote,
            isAnswered: true,
            isCorrect: true,
            isExpanded: false, // 答对后默认不展开，用户点击后展开
            resultMessage: '答对啦！' // 第一次答对时显示
          };

          this.setData({
            dailyQuote: updatedQuote
          });

          // 显示成功消息
          Message.success({
            context: this,
            content: '答对啦！',
            duration: 2000
          });

          // 3秒后隐藏"答对啦"消息
          setTimeout(() => {
            this.setData({
              'dailyQuote.resultMessage': ''
            });
          }, 3000);
        } else {
          // 答案错误，保持原样
          Message.warning({
            context: this,
            content: '答案不正确，请继续尝试',
            duration: 2000
          });
        }
      } else {
        // 如果接口返回失败，显示错误信息
        console.warn('后端接口返回失败');
        Message.error({
          context: this,
          content: '提交答案失败，请重试',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('检查答案失败:', error);
      
      // 任何错误都显示错误信息
      Message.error({
        context: this,
        content: '提交答案失败，请重试',
        duration: 2000
      });
    }
  },

  /**
   * 弹窗状态变化处理
   */
  onPopupChange(e) {
    this.setData({
      showFullPopup: e.detail.visible
    });
  },

  /**
   * 检查是否需要显示欢迎卡片
   */
  checkWelcomeCard() {
    // 检查是否应该显示欢迎卡片（小程序启动时设置）
    if (app.globalData.shouldShowWelcomeCard) {
      // 延迟显示，让页面先加载完成
      setTimeout(() => {
        this.setData({ showWelcomeCard: true });
      }, 1200);
      
      // 显示后重置标志，避免重复显示
      app.globalData.shouldShowWelcomeCard = false;
    }
  },

  /**
   * 欢迎卡片关闭事件
   */
  onWelcomeCardClose() {
    this.setData({ showWelcomeCard: false });
  },

  /**
   * 检查隐私协议（首页显示时）
   */
  async checkPrivacyAgreementOnShow() {
    try {
      // 防止重复检查
      if (this.data.privacyChecked) {
        return;
      }

      const userId = wx.getStorageSync('userId');
      if (!userId) {
        return;
      }

      // 标记已检查，防止重复
      this.setData({ privacyChecked: true });

      // 检查本地是否已同意最新版本协议
      const localAgreementTime = wx.getStorageSync('privacyAgreementTime');
      const localAgreementVersion = wx.getStorageSync('privacyAgreementVersion');
      const currentVersion = '1.0';

      if (localAgreementTime && localAgreementVersion === currentVersion) {
        return;
      }

      // 检查后端记录
      try {
        const userProfileAPI = require('~/api/userProfile.js').default;
        const response = await userProfileAPI.checkUserAgreement('privacy', currentVersion);
        
        if (response && response.code === 200 && response.data === true) {
          // 更新本地记录
          wx.setStorageSync('privacyAgreementTime', new Date().toISOString());
          wx.setStorageSync('privacyAgreementVersion', currentVersion);
          return;
        }
      } catch (error) {
        console.warn('检查后端协议状态失败:', error);
      }

      // 跳转到协议页面
      this.navigateToPrivacyAgreement();
    } catch (error) {
      console.error('检查隐私协议失败:', error);
    }
  },

  /**
   * 跳转到隐私协议页面
   */
  navigateToPrivacyAgreement() {
    wx.navigateTo({
      url: '/pages/privacy-agreement/index?showActions=true&isFirstTime=true',
      fail: (error) => {
        console.error('跳转协议页面失败:', error);
        // 如果跳转失败，显示简单提示
        wx.showToast({
          title: '请先同意隐私协议',
          icon: 'none',
          duration: 2000
        });
      }
    });
  }
});
